package lowijs.XfireClient.packet;

import lowijs.XfireClient.*;
import lowijs.XfireClient.event.*;

public class FriendslistPacket extends Packet {
	private final FriendManager fm = FriendManager.getInstance();
	
	public FriendslistPacket(byte[] data) {
		int numFriends = fromLowHigh(data[13], data[14]);
		int pos = 15;
		
		// add friends
		for (int i = 0; i < numFriends; i++) {
			int loginLen = fromLowHigh(data[pos], data[pos + 1]);
			byte[] loginBytes = new byte[loginLen];
			System.arraycopy(data, pos + 2, loginBytes, 0, loginBytes.length);
			fm.addFriend(new Friend(new String(loginBytes)));
			pos += loginLen + 2;
		}
		
		pos += 9; // go to nicks
		
		// set friends' nicknames
		for (int i = 0; i < numFriends; i++) {
			Friend f = fm.getFriend(i);
			
			int nickLen = fromLowHigh(data[pos], data[pos + 1]);
			byte[] nickBytes = new byte[nickLen];
			System.arraycopy(data, pos + 2, nickBytes, 0, nickBytes.length);
			f.setNick(new String(nickBytes));
			pos += nickLen + 2;
		}
		
		pos += 11; // go to userids
		
		// set friends' userids
		for (int i = 0; i < numFriends; i++) {
			Friend f = fm.getFriend(i);
			
			byte[] userid = new byte[4];
			System.arraycopy(data, pos, userid, 0, 4);
			f.setUserid(userid);
			pos += 4;
		}
		
		EventManager.fireEvent(new DatalessEvent(XfireEvent.XF_FLRECV));
	}
}
